package borge.web.teamspirit.client.page.team.widgets;

import java.util.List;

import borge.web.teamspirit.client.SessionData;
import borge.web.teamspirit.client.TeamSpirit;
import borge.web.teamspirit.client.TeamSpiritConstants;
import borge.web.teamspirit.client.data.TeamPlayer;
import borge.web.teamspirit.client.interfaces.PersistentData;
import borge.web.teamspirit.client.interfaces.ServerCallbackHandler;
import borge.web.teamspirit.client.interfaces.WidgetEventHandler;
import borge.web.teamspirit.client.interfaces.PersistentData.DataKey;
import borge.web.teamspirit.client.interfaces.WidgetEventHandler.WidgetEventType;
import borge.web.teamspirit.client.page.shared.widgets.ListDataWidget;
import borge.web.teamspirit.client.page.team.TokenData;
import borge.web.teamspirit.client.servercomm.DBQuery;
import borge.web.teamspirit.client.servercomm.ServerComm;

/**
 * Display a list of players in the team
 * @author andreas
 *
 */
@SuppressWarnings("unchecked")
public class ListPlayersWidget extends ListDataWidget<PersistentData> {
	
    //private List<Player> iPlayers;
    
    public ListPlayersWidget(WidgetEventHandler aEventHandler, List<PersistentData> aPlayers){
        super(aEventHandler, aPlayers, DataKey.TEAMPLAYER, TokenData.assembleTeamToken(TokenData.EDIT, TokenData.PLAYER), 
                WidgetEventType.DELETE_PLAYER,
                TokenData.assembleTeamToken(TokenData.SHOW, TokenData.PLAYER));
        
        initWidget(iPanel);
    }
    
    protected void createDataTable(){
    	
    	SessionData.sCurrentTeam.setPlayers(iData);
    	
    	reset();
    	
		TeamSpiritConstants lcs = TeamSpirit.getConstants();
		int row = 0;
		int col = 0;

		row++;

		for (PersistentData pd : iData) {
			col = 0;

			TeamPlayer p = (TeamPlayer)pd;
			
			iTable.setText(row, col++, p.getPersonName());//p.getNickName());
			addButtons(row++, col, p.getEncodedKey());

		}

    	
    }
    
    @Override
    public boolean needsServerUpdate(){
    	
    	if(iData == null){
    		if(SessionData.getTeamPlayers() == null){
    			return true;
    		}
    		else{
    			iData = SessionData.getTeamPlayers();
    			createDataTable();
    		}
    	}
    	
    	return false;
    	
    }
    
	@Override
	public void requestServerData(ServerCallbackHandler aHandler) {
		
		DBQuery query = new DBQuery(DataKey.TEAMPLAYER, TeamPlayer.class.getName());
		query.addFilter("iTeamKey", DBQuery.EQUALS, "teamKey", "String", SessionData.sCurrentTeam.getEncodedKey(), null);
		ServerComm.getObjectList(query, aHandler);
		
	}

}
